/***************************************************************************
                           setup.c  -  description
                             -------------------
    begin             : 19.07.2008
    copyright         : (C) 2008 by MHS-Elektronik GmbH & Co. KG, Germany
    autho             : Klaus Demlehner, klaus@mhs-elektronik.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software, you can redistribute it and/or modify  *
 *   it under the terms of the GNU Lesser General Public License           *
 *   version 2.1 as published by the Free Software Foundation.             *
 *                                                                         *
 ***************************************************************************/
#include <gtk/gtk.h>
#include "main.h"
#include "gtk_util.h"
#include "gui.h"
#include "configfile.h"
#include "setup.h"


int LoadConfigFile(gchar *filename)
{
ConfigFile *cfgfile;
char section[10];
gchar *tmpbuf;
int i, mode;

if (!filename)
  return(-1);
tmpbuf = NULL;                
cfgfile = cfg_open_file(filename);
if (!cfgfile)
  return(-1);
if (cfg_read_int(cfgfile, "Global", "AdRef", &i))
  Config.AdRef = i;
if (cfg_read_int(cfgfile, "Global", "PwmSpeed1", &i))
  Config.PwmSpeed1 = i;
if (cfg_read_int(cfgfile, "Global", "PwmSpeed2", &i))
  Config.PwmSpeed2 = i;
for (i = 0; i < IO_PIN_COUNT; i++)
  {
  g_snprintf(section, 10, "IDX%u", i);
  if (cfg_read_string(cfgfile, section, "Name", &tmpbuf))
    {
    save_free(IoPin[i].Name);
    IoPin[i].Name = g_strdup(tmpbuf);
    save_free(tmpbuf);
    }
  if (cfg_read_int(cfgfile, section, "Mode", &mode))
    IoPin[i].Mode = mode;
  }
cfg_free(cfgfile);
return(0);   
}


int SaveConfigFile(gchar *filename)
{
ConfigFile *cfgfile;
char section[10];
int i, res;

res = 0;
if (!filename)
  return(-1);
cfgfile = cfg_open_file(filename);

if (!cfgfile)
  cfgfile = cfg_new();

cfg_write_int(cfgfile, "Global", "AdRef", Config.AdRef);
cfg_write_int(cfgfile, "Global", "PwmSpeed1", Config.PwmSpeed1);
cfg_write_int(cfgfile, "Global", "PwmSpeed2", Config.PwmSpeed2);
for (i = 0; i < IO_PIN_COUNT; i++)
  {
  g_snprintf(section, 10, "IDX%u", i);
  if (IoPin[i].Name)
    cfg_write_string(cfgfile, section, "Name", IoPin[i].Name);
  else
    cfg_remove_key(cfgfile, section, "Name");
  cfg_write_int(cfgfile, section, "Mode", IoPin[i].Mode);
  }
if (cfg_write_file(cfgfile, filename) == FALSE)
  res = -1;
cfg_free(cfgfile);
return(res);
}
